#include <GL/glew.h>
#include <GL/glut.h>
#include <iostream>
#include <bitset>
#include <set>
#include "shader.h"
#include "utility.h"
#include "mesh.h"
#include "context.h"
#include "world.h"
#include "select.h"


unsigned point_select (int x, int y)
{
	unsigned nWidth = 1; 
	unsigned nHeight = 1;
	unsigned char * pRGB = new unsigned char [4 * (nWidth+1) * (nHeight + 1) + 4];

	glReadBuffer( GL_BACK );
	glReadPixels( x , y, nWidth, nHeight, GL_RGBA, GL_UNSIGNED_BYTE, pRGB);

	int color_number = (pRGB[ 0 ]<<16) + (pRGB[ 1 ]<<8) + (pRGB[ 2 ]);
	//World->SelectBackBufferObject( ColorNumber );
	int sample_idx = int(pRGB[3]) - 1;
	//std::cout<<int(pRGB[ 0 ])<<' '<<int(pRGB[ 1 ])<<' '<<int(pRGB[2])<<' '<<int(pRGB[3])<<std::endl;
	if (color_number)
	{
		c.set_face_color(color_number -1 , RGB(255,255,255));
		if (sample_idx >=0 )
			c.set_sample_color(color_number - 1, sample_idx, RGB(255,0,0));
	}

	delete[] pRGB;
	return color_number ;
}
void region_select (int x, int y, int width, int height)
{
	std::set <unsigned> face_idx;
	for (int i = x - width; i <= x + width; ++i)
	{
		for (int j = y - height; j <= y + height; ++j)
		{
			if ( (i- x) * (i-x) + (j-y) * (j-y) < width * width && 
				(i >=0 && j >=0 ) && (i < WINDOW_WIDTH && j < WINDOW_HEIGHT))
			{
				// The color are drawn from index 1 while the face are indexed from 0; 
				// We need to minus 1 to get the selected face idx; 
				unsigned face = point_select(i,j) ;
				if (face)
				{
					face_idx.insert(face - 1);
				};
			}
		}
	}
	for (std::set <unsigned>::iterator face_iter = face_idx.begin(); face_iter != face_idx.end(); ++face_iter)
	{
		std::cout<<(* face_iter)<<' ' ;
	}
	std::cout<<std::endl;
}

void select_backbuffer(int button, int state, int x, int y)
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();
	//glTranslatef(0.0f, 0.0f, -2.0f);
	//glRotatef(angle, 0.0f, 1.0f, 1.0f); 

	//drawSence(GL_RENDER);

	c.draw_backbuffer(0);

	glDisable(GL_DITHER);
	if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
	{
		//point_select(x, WINDOW_HEIGHT - y);
		region_select(x, WINDOW_HEIGHT - y, 50, 50);
	}
	glEnable(GL_DITHER);
}